package com.qf.amqp;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.concurrent.TimeoutException;

public class MainActivity extends AppCompatActivity {

    public final String exChangeName = "android-exchange";
    public final int REQUEST_OVERLAY_PERMISSION = 303;
    public final String QUEUE_NAME = "android.queue";
    public final String routingKey = "android-route";
    private Channel channel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(() -> {
            try {
                getChannel();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
//            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
//                    Uri.parse("package:" + this.getPackageName()));
//            startActivityForResult(intent, REQUEST_OVERLAY_PERMISSION);
//        }
    }

    //创建 RabbitMQ 连接和通道
    public void getChannel() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("43.139.170.86");
        factory.setPort(5672);
        factory.setUsername("lx");
        factory.setPassword("lx0826");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
        System.out.println(channel);
        //声明交换器
        channel.exchangeDeclare(exChangeName, "topic", true);

//        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
//        String QUEUE_NAME = channel.queueDeclare().getQueue();
        //绑定队列-交换器-路由键
        channel.queueBind(QUEUE_NAME, exChangeName, routingKey);
        //收到消息的回调
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
//            Order order = JSON.parseObject(message, Order.class);
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
//            runOnUiThread(() -> Toast.makeText(this, order.getId()+"", Toast.LENGTH_SHORT).show());
            showNotification("您有一条新消息", message.replace("\"", ""));
        };
        //消费消息
        channel.basicConsume(QUEUE_NAME, false, deliverCallback, consumerTag -> {
        });


    }

    // todo 要展示提醒类型的通知 需要手动打开在屏幕上方显示的权限
    public void showNotification(String title, String message) {

        String CHANNEL_ID = "chat";
        //适配8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    "聊天信息",
                    NotificationManager.IMPORTANCE_HIGH);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }

        /**
         * 注意写上 channel_id，适配8.0，不用担心8.0以下的，找不到 channel_id 不影响程序
         */
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
//                .setContentIntent(pi)
                .setPriority(NotificationCompat.PRIORITY_HIGH) // 设置通知的优先级为高
                .setContentTitle(title)
                .setContentText(message)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        //通过 builder.build() 拿到 notification
        mNotificationManager.notify(1, mBuilder.build());
    }
}